/**
 * 
 */
package pers.vic.test.freemarker;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author Vic.xu
 *
 */
public class FreemarkerUtil {
	
	private final static Logger logger = LoggerFactory.getLogger(FreemarkerUtil.class);

    /**
     * 获取模板内容
     *
     * @param template 模板文件
     * @param map      模板参数
     * @return 渲染后的模板内容
     * @throws IOException       IOException
     * @throws TemplateException TemplateException
     */
    public static String getTemplate(String template, Map<String, Object> map) throws IOException, TemplateException {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_26);
        String templatePath = FreemarkerUtil.class.getResource("/").getPath();
        logger.info("FreemarkerUtil template  = " + template);
        logger.debug("templatePath = " + templatePath);
        cfg.setDirectoryForTemplateLoading(new File(templatePath));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setLogTemplateExceptions(false);
        cfg.setWrapUncheckedExceptions(true);
        Template temp = cfg.getTemplate(template);
        StringWriter stringWriter = new StringWriter();
        temp.process(map, stringWriter);
        return stringWriter.toString();
    }
    
    public static void main(String[] args) throws IOException, TemplateException {
		String template = "freemarker/test.html";
		Map<String, Object> map= new HashMap<>();
		List<String> interestList = new ArrayList<String>();
		interestList.add("书法");
		interestList.add("诗歌");
		interestList.add("dota");
		interestList.add("1234567");
		map.put("interestList", interestList);
		map.put("name", "张三");
		
		String string =getTemplate(template, map);
		System.out.println(string);
		
    }
}
